package com.universest.swordholder.viewmodel

import android.content.Intent
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import java.lang.reflect.InvocationTargetException

@Composable
inline fun <reified T : ViewModel> intentViewModel(intent: Intent): T {
    return viewModel(factory = IntentViewModelFactory(intent))
}

class IntentViewModelFactory(private val intent: Intent?): ViewModelProvider.Factory {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        try {
            if (BaseViewModel::class.java.isAssignableFrom(modelClass)) {
                val constructor = modelClass.getConstructor(Intent::class.java)
                return constructor.newInstance(intent)
            }
        } catch (e: NoSuchMethodException) {
            Log.e("IntentViewModelFactory", "ViewModel constructor with Intent parameter not found: ${e.message}")
        } catch (e: InstantiationException) {
            Log.e("IntentViewModelFactory", "Error instantiating ViewModel: ${e.message}")
        } catch (e: IllegalAccessException) {
            Log.e("IntentViewModelFactory", "Illegal access to ViewModel constructor: ${e.message}")
        } catch (e: InvocationTargetException) {
            Log.e("IntentViewModelFactory", "Exception thrown by ViewModel constructor: ${e.message}")
            throw RuntimeException("Failed to create ViewModel due to constructor exception", e)
        }
        try {
            return modelClass.getDeclaredConstructor().newInstance()
        } catch (e: Exception) {
            Log.e("IntentViewModelFactory", "Error creating ViewModel with default constructor: ${e.message}")
            throw RuntimeException("Failed to create ViewModel", e)
        }
    }

}